#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //测试OObject::property属性
    Student stu;
    stu.testProperty();

    //这里为了测试添加的动态属性是跟对象实例绑定，上面stu对象里添加了动态属性height，但是在stu2对象就不可见
    Student stu2;
    stu2.testProperty2();
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{

}

Student::Student(QObject *parent) : QObject(parent), m_nAge(15)
{

}

void Student::SetName(QString strName)
{
    m_strName = strName;
    emit SignalNameChanged(strName);
//    update(); // 触发界面重绘
}

QString Student::GetName()
{
    return m_strName;
}

void Student::SetAge(int nAge)
{
    m_nAge = nAge;
    emit SignalAgeChanged(nAge);
}

int Student::GetAge()
{
    return m_nAge;
}

void Student::SlotNameChanged(QString strName)
{
    qDebug() << "Name changed = " << strName;
}

void Student::SlotAgeChanged(int nAge)
{
    qDebug() << "Age changed = " << nAge;
}

// 类属性测试
void Student::testProperty()
{
    QObject::connect(this, &Student::SignalNameChanged, this, &Student::SlotNameChanged);

    // 下面两行代码的操作意义一样，都能达到设置 Student 成员变量 m_strName 的效果
    this->SetName(QString("zhangsan"));
    bool bRtn = this->setProperty("name", QString("Zhangsan"));       // 也会调用 Student 的 SetName 成员函数

    // 下面两行代码的操作意义一样，都能达到获取 Student 成员变量 m_strName 的值的效果
    QString strName = this->property("name").toString();
    qDebug() << "use QObject::setProperty get filed name value:[%s]" << strName;
    strName = this->GetName();
    qDebug() << "use Student::GetName get filed name value:[%s]" << strName;

    // 动态属性是在运行时定义的，它只属于正在运行的类的实例
    // 动态设置属性，该属性本身不存在, 此时返回值为 false
    bRtn = this->setProperty("height", 180);
    qDebug() << "use setProperty set unexits filed height, ret value:" << bRtn;
    int nHeight = this->property("height").toInt();
    qDebug() << "use property get field height:" << nHeight;
}

void Student::testProperty2()
{
    int nHeight = this->property("height").toInt();
    qDebug() << "testProperty2 use property get field height:" << nHeight;
}

